

package yf.mall.service.impl;
import com.yf.response.RRException;
import com.yf.utils.ShiroUtils;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import yf.mall.common.Const;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.AnswerStatusEnum;
import yf.mall.enums.QuestionStatusEnum;
import yf.mall.service.NoticeService;
import yf.mall.service.SysUsersService;
import  yf.mall.vo.down.QuestionDown;

import java.text.SimpleDateFormat;
import java.util.*;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

import yf.mall.vo.QuestionVo;
import yf.mall.service.QuestionService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Tue Dec 15 13:15:22 CST 2020
 */
@Service
public class QuestionServiceImpl extends BaseServiceImpl<QuestionEntity> implements QuestionService {

    private QuestionDao dao;


    @Autowired
    public void setDao(QuestionDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }

    @Autowired
    private UserDao userDao;
    @Autowired
    private AnswerDao answerDao;
    @Autowired
    private SysUsersDao sysUsersDao;
    @Autowired
    private MallGoodsDao mallGoodsDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private NoticeService noticeService;

    @Override
    public List<QuestionVo> findVo(QuestionVo vo){

        List<QuestionVo> questionVos = dao.findVo(vo);
        if (questionVos != null && questionVos.size() > 0){
            for (QuestionVo questionVo : questionVos) {
                ShopEntity shop = new ShopEntity();
                MallGoodsEntity goodsEntity = mallGoodsDao.get(questionVo.getQuestion().getGoodsId());
                if (goodsEntity != null){
                    questionVo.setGoodsName(goodsEntity.getName());
                }
                if (goodsEntity.getUserId() != null && !goodsEntity.getUserId().equals(Const.ADMIN_ID)){
                    shop = shopDao.findByUserId(goodsEntity.getUserId());
                }
                questionVo.getQuestion().setShop(shop);
                //是否存在未审核的回答
                List<AnswerEntity> answers = answerDao.queryByQuestionId(questionVo.getQuestion().getId(),AnswerStatusEnum.AUDIT.getIndex());
                if (answers != null && answers.size() > 0){
                    questionVo.getQuestion().setIsAnswerAudit(1);
                }
                //是否回答
                List<AnswerEntity> isAnswer = answerDao.queryByQuestionId(questionVo.getQuestion().getId(),null);
                if (isAnswer != null && isAnswer.size() > 0){
                    questionVo.getQuestion().setIsAnswer(1);
                }
            }
        }
        return questionVos;
    }

    @Override
    public QuestionVo getVo(Long id){
        QuestionVo vo = dao.getVo(id);
        List<AnswerEntity> answerEntities = answerDao.queryByQuestionId(vo.getQuestion().getId(), null);
        vo.getQuestion().setList(answerEntities);
        MallGoodsEntity goodsEntity = mallGoodsDao.get(vo.getQuestion().getGoodsId());
        if (goodsEntity != null){
            vo.setGoodsName(goodsEntity.getName());
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(QuestionVo vo){
        return dao.save(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(QuestionVo vo){
        Long sys_user = ShiroUtils.getUserId();
        Long userId = sysUsersDao.findBySysUserId(sys_user);
        MallGoodsEntity goodsEntity = mallGoodsDao.get(vo.getQuestion().getGoodsId());
        UserEntity userEntity = null;
        if (goodsEntity.getUserId() != null && !goodsEntity.getUserId().equals(Const.ADMIN_ID)){
            userEntity = userDao.get(goodsEntity.getUserId());
        }
        //不是公司账号 修改的不是该账号下的产品
        if (userId != null && !userId.equals(goodsEntity.getUserId())){
            throw new RRException("非法操作");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        //对已回复的进行审核修改 仅限公司才能操作
        if (userId ==null){
            if (vo.getQuestion().getList() != null && vo.getQuestion().getList().size() > 0){
                for (AnswerEntity answerEntity : vo.getQuestion().getList()) {
                    //如果回答未通过则发送通知
                    if (answerEntity.getStatus()==AnswerStatusEnum.NO.getIndex()){
                        if (userEntity != null){
                            noticeService.noticeAnswerExa(userEntity.getOpenId(),answerEntity.getRemark(),time,answerEntity.getContent());
                        }
                    }
                    //如果是已通过的状态 则修改之前未通过的原因
                    if (answerEntity.getStatus() == AnswerStatusEnum.YES.getIndex()){
                        if (answerEntity.getRemark() != null){
                            answerEntity.setRemark(null);
                        }
                    }
                    answerDao.update(answerEntity);
                }
            }
        }
        //新增的回复添加
        if (vo.getAnswerContent() != null && !vo.getAnswerContent().equals("")){
            AnswerEntity answerEntity = new AnswerEntity();
            answerEntity.setTime(new Date());
            //如果是公司回复则为已通过
            if (userId==null){
                answerEntity.setStatus(AnswerStatusEnum.YES.getIndex());
            }else {
                answerEntity.setStatus(AnswerStatusEnum.AUDIT.getIndex());
            }
            answerEntity.setQuestionId(vo.getQuestion().getId());
            answerEntity.setContent(vo.getAnswerContent());
            answerDao.save(answerEntity);
        }
        //问题审核未通过发送通知给提问者
        if (vo.getQuestion().getStatus() == QuestionStatusEnum.NO.getIndex()){
            userEntity = userDao.get(vo.getQuestion().getUserId());
            noticeService.noticeQuestionExa(userEntity.getOpenId(),vo.getQuestion().getRemark(),time,vo.getQuestion().getContent());
        }
        return dao.update(vo.getEntity());
    }



    @Override
    public void downLoad(HttpServletResponse response, List<QuestionVo> list) {
        try {
            List<QuestionDown> datas = list.stream().map(item -> new QuestionDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel" );
            response.setCharacterEncoding("utf-8" );
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8" );
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx" );
            EasyExcel.write(response.getOutputStream(), QuestionDown.class).sheet("模板" ).doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    /**内部方法**/



    /**外部方法实现**/
    @Override
    public List<QuestionEntity> queryByGoodsId(Long goodsId, Integer status) {
        return dao.queryByGoodsId(goodsId,status);
    }

    @Override
    public Integer totalQuestion(Long goodsId) {
        return dao.totalQuestion(goodsId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QuestionEntity apiSave(Long userId, Long goodsId, String content) {
        UserEntity userEntity = userDao.get(userId);

        QuestionEntity question = new QuestionEntity();
        question.setAvatar(userEntity.getAvatar());
        question.setContent(content);
        question.setUserId(userId);
        question.setUserId(userId);
        question.setUserName(userEntity.getName());
        question.setTime(new Date());
        question.setGoodsId(goodsId);
        question.setStatus(QuestionStatusEnum.AUDIT.getIndex());
        dao.save(question);

        //不是公司产品 发送问题通知给店铺
        MallGoodsEntity mallGoodsEntity = mallGoodsDao.get(goodsId);
        if (mallGoodsEntity.getUserId() != null && !mallGoodsEntity.getUserId().equals(Const.ADMIN_ID)){
            userEntity = userDao.get(mallGoodsEntity.getUserId());
        }else {
            //公司产品给客服1号发送通知
            userEntity = userDao.findByCode("zmz782751");
        }
        noticeService.noticeQuestion(userEntity.getOpenId(),content);
        return question;
    }

    @Override
    public List<QuestionEntity> myQuiz(Long userId, Integer temp) {
        List<QuestionEntity> list = new ArrayList<>();
        Integer status = AnswerStatusEnum.YES.getIndex();
        if (temp == 1){
            status = null;
        }
        if (temp != 2){
            list = this.dao.questionMe(userId);
        }else{
            list = this.dao.myQuestion(userId);
        }
        if (list != null && list.size() > 0){
            for (QuestionEntity question : list) {
                List<AnswerEntity> answerEntities = answerDao.queryByQuestionId(question.getId(), status);
                MallGoodsEntity mallGoodsEntity = mallGoodsDao.get(question.getGoodsId());
                question.setGoods(mallGoodsEntity);
                //如果没有我的回答 则直接返回null
                if (temp==3){
                    if (answerEntities == null || answerEntities.size() == 0){
                        return null;
                    }
                }
                question.setList(answerEntities);
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(Long[] ids) {
        dao.deleteBatch(ids);
        dao.deleteByQuesIdBatch(ids);
    }


}
